package com.sky.Aspect;


import com.sky.Annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {



    @Pointcut( "execution(* com.sky.controller.admin.*.*(..)) && @annotation(com.sky.Annotation.AutoFill) ")
    public void pt(){

    }



    @Before("pt()")
    public void before(JoinPoint joinPoint) {
        log.info("开始进行公共字段填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();

        Object[] args = joinPoint.getArgs();
        Object po = args[0];

        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        if(operationType==OperationType.INSERT){
           try {
               Method setCreateTime = po.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
               Method setCreateUser = po.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
               Method setUpdateTime = po.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
               Method setUpdateUser = po.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
               setUpdateTime.invoke(po,now);
               setUpdateUser.invoke(po,currentId);
               setCreateTime.invoke(po,now);
               setCreateUser.invoke(po,currentId);
           }catch (Exception e){
               e.printStackTrace();
           }
        }else if(operationType==OperationType.UPDATE){

            try {

                Method setUpdateTime = po.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = po.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(po,now);
                setUpdateUser.invoke(po,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }



    }
}
